import { CommonModal } from "@/views/components/CommonModal";
import {
	Button,
	Col,
	Popconfirm,
	Form,
	Input,
	Row,
	InputNumber,
	Image,
	Alert,
	Space,
	Modal,
	Anchor,
	Upload,
	Radio,
	message
} from "antd";
import { useCallback, useState, useRef } from "react";
import Typography from "@/pages/OrderModule/common/components/Typography";
import CombForm from "./CombForm";
import Style from "./index.module.less";
import { useEffect } from "react";
import { cloneDeep } from "lodash";
import { combinationBatchSubmit } from "../service";

let submitCount = 0;
function uuid() {
	return new Date().getTime() + Math.random();
}
const BatchModifyProducts = ({ parentForm, handleOk, handleCancel, handleCancelAll, sonGoodsList, isOpen, specsList }) => {
	const [formList, setFormList] = useState(
		specsList.map((specs, i) => ({
			uuid: uuid(),
			flag: true,
			submitCount: -1,
			combinations: isOpen
				? sonGoodsList.map(e => ({ ...e, skuId: e.id })).filter(x => x.specs == specs)
				: specsList[i].map(e => ({ ...e })),
			parentFormData: parentForm.getFieldsValue() || {}
		}))
	);
	useEffect(() => {}, [sonGoodsList]);
	const refs = formList.map(e => useRef(null));
	const handleCreate = useCallback(() => {
		// 使用refs数组中的ref
		const promiseList = [];
		submitCount++;
		refs.forEach((ref, index) => {
			const flag = formList[index].flag;
			if (flag) {
				ref.current?.submit();
			}
		});
	}, [formList, refs]);

	const onSubmitCreate = useCallback(
		combinationBatchList => {
			combinationBatchSubmit({ combinationBatchList }).then(res => {
				const { success, msg } = res;
				if (success) {
					message.success(msg);
					handleCancelAll();
				} else {
					message.warning(msg);
				}
			});
		},
		[formList]
	);

	const onFormDataDelete = index => {
		const count = formList.filter(e => e.flag).length;
		if (count > 1) {
			setFormList(pre => {
				pre[index].flag = false;
				return cloneDeep(pre);
			});
		} else {
			message.warning("至少保留一个商品信息");
		}
	};
	const onFormFinish = useCallback(
		(formData, index) => {
			setFormList(pre => {
				return pre.map((e, i) => {
					if (i === index) {
						return { ...e, ...formData, submitCount };
					}
					return e;
				});
			});
		},
		[setFormList]
	);

	useEffect(() => {
		const d = formList.filter(e => e.flag);
		if (d.every(e => e.submitCount === submitCount)) {
			onSubmitCreate(d);
		}
	}, [formList]);

	// 		bodyStyle={{ maxHeight: "calc(100vh - 360px)", overflowY: "auto" }}
	return (
		<CommonModal
			title={{ title: "组合预览" }}
			open={true}
			width="80%"
			className="views-table-dialog"
			onCancel={handleCancel}
			footer={
				<Row justify="end">
					<Col>
						<Space>
							<Button size="middle" type="primary" onClick={handleCreate}>
								创建
							</Button>
						</Space>
					</Col>
				</Row>
			}
		>
			<Alert
				showIcon
				message={
					<Typography as="s1">
						<div>1.组合预览里如果有个别组合不需要，可以删除后再保存；1.组合预览里如果有个别组合不需要，可以删除后再保存；</div>
						<div>
							2.组合编号不能重复，如果店铺商品编码与组合编号一致的，则会自动匹配（组合编号注意不要与{APP_TITLE}供应商商品编号一样）；
						</div>
						<div>3.保存后会批量生成多个组合，请仔细检查组合商品是否正确</div>
					</Typography>
				}
			/>
			{formList.map((item, formIndex) => {
				if (!item.flag) return <></>;
				return (
					<CombForm
						ref={refs[formIndex]}
						key={item.uuid}
						parentFormData={item.parentFormData}
						formIndex={formIndex}
						isOpen={isOpen}
						sonGoodsList={item.combinations}
						onDelete={onFormDataDelete}
						onFormFinish={onFormFinish}
					></CombForm>
				);
			})}
		</CommonModal>
	);
};

export default BatchModifyProducts;
